package cn.sc.allinpay.allfavour.business.payment;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.allinpay.usdk.core.data.ResponseData;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.common.utils.AmtUtils;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.business.common.app.Global;
import cn.sc.allinpay.allfavour.business.common.data.OrderData;
import cn.sc.allinpay.allfavour.business.common.data.PayInfo;
import cn.sc.allinpay.allfavour.business.common.data.PosData;
import cn.sc.allinpay.allfavour.business.common.data.PosInfo;
import cn.sc.allinpay.allfavour.business.common.data.SpOrderInfo;
import cn.sc.allinpay.allfavour.business.common.data.TransRecord;
import cn.sc.allinpay.allfavour.business.common.utils.SpUtils;
import cn.sc.allinpay.allfavour.business.main.MainActivity;
import cn.sc.allinpay.allfavour.business.paymentresult.PaymentResultActivity;
import cn.sc.allinpay.allfavour.module.allin.AllinUtils;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 去支付 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class PaymentPresenter extends PaiPresenter<PaymentContract.View> implements PaymentContract.Presenter {
    public static final int REQ_SALE = 0x01;//消费
    public static final int REQ_SCAN = 0x02;//扫码支付ll

    private PaymentModel model = new PaymentModel();
    private OrderData order;//交易订单对象
    private PosData posData;//Pos对象
    private TransRecord transRecord;//交易记录，部分抵扣成功和交易详情进入时
    private BigDecimal paidAmt;//待支付金额
    private BigDecimal balAmt;//剩余金额
    private IPrinter printer;

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                order = bundle.getParcelable(Constant.BundleKey.PAY_ORDER);
                transRecord = bundle.getParcelable(Constant.BundleKey.TRANS_RECORD);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (data != null && data.getExtras() != null) {
                    Bundle extras = data.getExtras();
                    ResponseData result = (ResponseData) extras.getSerializable("RESPONSE");
                    if (result != null) {
                        if (result.getValue("REJCODE").equals("00")) {
                            posData = new PosData();
                            posData.setTerminalId(result.getValue("TER_ID"));//终端号
                            posData.setMerchantId(result.getValue("MERCH_ID"));//商户id
                            posData.setMerchantName(result.getValue("MERCH_NAME"));//商户名称
                            posData.setCashAmt(view.getCashAmt());
                            posData.setAmount(balAmt.toString());//金额
                            posData.setOrderId(order.getOrderId());
                            if (REQ_SALE == requestCode) {//刷卡消费成功
                                posData.setTransType("消费");//交易类型
                                posData.setTraceNo(result.getValue("TRACE_NO"));//凭证号
                                posData.setBatchNo(result.getValue("BATCH_NO"));//批次号
                                posData.setReferenceNo(result.getValue("REF_NO"));//参考号
                                String dateTime = AllinUtils.getSysYear() + result.getValue("DATE") + result.getValue("TIME");
                                posData.setDateTime(dateTime);//交易时间 格式yyyyMMddHHmmss
                                posData.setCardNo(result.getValue("CARDNO"));//卡号
                                posData.setIssue(result.getValue("ISS_NO"));//发卡行
                                posData.setTransactionNumber(result.getValue("TRANS_TICKET_NO"));//交易单号
                                if (transRecord != null) {
                                    //支付成功
                                    updRecord(2);
                                } else {
                                    //无抵扣，支付成功，
                                    saveRecord(order.getOrderId(), 2, 0);
                                }
                                Date myDate1 = new Date();
                                DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
                                try {
                                    myDate1 = dateFormat1.parse(dateTime);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                view.loading();
                                model.payNotify(order.getOrderId(), "bank", "PAY", dateFormat2.format(myDate1), AmtUtils.changeY2F(posData.getCashAmt()), AmtUtils.changeY2F(posData.getAmount()), posData.getTransactionNumber(), new MpCallBack<JSONObject, String>() {
                                    @Override
                                    public void onSuccess(JSONObject resp) {
                                        model.getGlobal().setPayInfo(null);
                                        SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, "");
                                        view.loaded();
                                        view.toast("消费成功");
                                        print();
                                    }

                                    @Override
                                    public void onFailure(String resp, String message) {
                                        view.loaded();
                                        view.prompt(message);
                                    }
                                });
                            } else if (REQ_SCAN == requestCode) {//扫码支付成功
                                view.loading();
                                String authCode = result.getValue("PAN");

                                model.spScan(authCode, balAmt.toString(), order.getSpOrderId() + "", order.getSpOrderCode() + "", new MpCallBack<SpOrderInfo, String>() {
                                    @Override
                                    public void onSuccess(SpOrderInfo orderInfo) {
                                        view.loaded();
                                        Bundle bundle = new Bundle();
                                        bundle.putParcelable(Constant.BundleKey.PAY_ORDER, order);
                                        bundle.putParcelable(Constant.BundleKey.TRANS_RECORD, transRecord);
                                        bundle.putParcelable(Constant.BundleKey.POS_DATA, posData);
                                        bundle.putParcelable(Constant.BundleKey.SP_ORDER_INFO, orderInfo);
                                        view.toActivity(PaymentResultActivity.class, bundle);
                                        view.finish();
                                    }

                                    @Override
                                    public void onFailure(String resp, String message) {
                                        view.btnScanClickable(true);
                                        view.loaded();
                                        view.prompt(message);
                                    }
                                });
                            }
                        } else {
                            view.btnScanClickable(true);
                            String error = result.getValue("REJCODE_CN");
                            view.toast(error);

                            if (REQ_SALE == requestCode) {
                                model.getGlobal().setPayInfo(null);
                                SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(""));
                            }
                        }
                    }
                } else {
                    view.btnScanClickable(true);
                }
            }
        };
    }

    @Override
    public void start() {
        if (initData()) {
            initView();
        } else {
            view.finish();
        }
    }

    /**
     * 数据初始化
     *
     * @return
     */
    private boolean initData() {
        if (order == null) {
            if (transRecord == null || TextUtils.isEmpty(transRecord.getOrderData())) {
                view.toast("订单数据为空");
                return false;
            }
            order = JSON.parseObject(transRecord.getOrderData(), OrderData.class);
        }
        paidAmt = new BigDecimal(order.getPaidAmt());
        balAmt = new BigDecimal(order.getPaidAmt());
        return true;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        view.showPaidAmt(AmtUtils.formatY(paidAmt));
        view.setCashMaxAmt(paidAmt.toString());
        view.showBalAmt(AmtUtils.formatY(balAmt));
        view.btnCashClickable(false);
    }

    @Override
    public void countBalAmt() {
        String cashAmt = view.getCashAmt();
        if (!TextUtils.isEmpty(cashAmt)) {
            balAmt = paidAmt.subtract(new BigDecimal(cashAmt));
        } else {
            balAmt = paidAmt.subtract(BigDecimal.ZERO);
        }
        view.showBalAmt(AmtUtils.formatY(balAmt));
        if (BigDecimal.ZERO.compareTo(balAmt) >= 0) {
            view.btnCashClickable(true);
            view.btnCardClickable(false);
            view.btnScanClickable(false);
        } else {
            view.btnCashClickable(false);
            view.btnCardClickable(true);
            view.btnScanClickable(true);
        }
    }

    @Override
    public void callSale() {
        if (model.getGlobal().getPayInfo() != null) {
            view.prompt(false, "您有一笔订单状态未校正，请返回首页点击收银按钮校正", new OnPromptListener("确定") {
                @Override
                public void onPositive(DialogInterface dialog, int which) {
                    super.onPositive(dialog, which);
                    dialog.dismiss();
                    view.toActivity(MainActivity.class, null);
                    view.finish();
                }
            });
            return;
        }
        DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date myDate1 = dateFormat1.parse(order.getRetTime());
            Date myDate2 = new Date();

            long between = (myDate2.getTime() - myDate1.getTime()) / 1000;
            long time = between / 60;

            if (time > 10) {
                view.prompt("订单已超过10分钟，不能继续支付");
                return;
            }

            PayInfo payInfo = new PayInfo();
            payInfo.setAmount(balAmt.toString());
            payInfo.setOrderId(order.getOrderId());
            payInfo.setType("pay");
            String orderJSON = JSON.toJSONString(order);
            String transRecordJSON = JSON.toJSONString(transRecord);
            payInfo.setOrderJSON(orderJSON);
            payInfo.setTransRecordJSON(transRecordJSON);
            posData = new PosData();
            posData.setCashAmt(view.getCashAmt());
            posData.setAmount(balAmt.toString());//金额
            posData.setOrderId(payInfo.getOrderId());
            String posDataJson = JSON.toJSONString(posData);
            payInfo.setPosDataJSON(posDataJson);
            model.getGlobal().setPayInfo(payInfo);
            SpUtils.put(view.getContext(), Constant.SPNAME, Constant.SpKey.PayInfo, JSON.toJSONString(payInfo));
            AllinUtils.cardPayment(view.getActivity(), order.getOrderId(), balAmt.toString(), REQ_SALE);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void callScan() {

        if (model.getGlobal().getPayInfo() != null) {
            view.prompt(false, "您有一笔订单状态未校正，请返回首页点击收银按钮校正", new OnPromptListener("确定") {
                @Override
                public void onPositive(DialogInterface dialog, int which) {
                    super.onPositive(dialog, which);
                    dialog.dismiss();
                    view.toActivity(MainActivity.class, null);
                    view.finish();
                }
            });
            return;
        }

        DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date myDate1 = dateFormat1.parse(order.getRetTime());
            Date myDate2 = new Date();

            long between = (myDate2.getTime() - myDate1.getTime()) / 1000;
            long time = between / 60;

            if (time > 10) {
                view.prompt("订单已超过10分钟，不能继续支付");
                return;
            }

            if (order.getSpOrderCode() != null || order.getSpOrderId() != null) {
                AllinUtils.callScan(view.getActivity(), REQ_SCAN);
            } else {
                view.btnScanClickable(false);
                view.loading("订单创建中...");
                model.spCreateOrder(balAmt.toString(), order.getOrderId(), new MpCallBack<SpOrderInfo, String>() {
                    @Override
                    public void onSuccess(SpOrderInfo orderInfo) {
                        view.loaded();
                        String orderCode = orderInfo.getOrderCode();
                        order.setSpOrderCode(orderCode);
                        order.setSpOrderId(orderInfo.getOrderId());
                        AllinUtils.callScan(view.getActivity(), REQ_SCAN);
                    }

                    @Override
                    public void onFailure(String response, String message) {
                        view.btnScanClickable(true);
                        view.loaded();
                        view.prompt(message);
                    }
                });
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void callCash() {

        if (model.getGlobal().getPayInfo() != null) {
            view.prompt(false, "您有一笔订单状态未校正，请返回首页点击收银按钮校正", new OnPromptListener("确定") {
                @Override
                public void onPositive(DialogInterface dialog, int which) {
                    super.onPositive(dialog, which);
                    dialog.dismiss();
                    view.toActivity(MainActivity.class, null);
                    view.finish();
                }
            });
            return;
        }

        DateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Date myDate1 = dateFormat1.parse(order.getRetTime());
            Date myDate2 = new Date();

            long between = (myDate2.getTime() - myDate1.getTime()) / 1000;
            long time = between / 60;

            if (time > 10) {
                view.prompt("订单已超过10分钟，不能继续支付");
                return;
            }

            posData = new PosData();
            Global global = model.getGlobal();
            PosInfo posInfo = global.getPosInfo();
            posData.setTerminalId(posInfo.getTer_id());//终端号
            posData.setMerchantId(posInfo.getMer_id());//商户id
            posData.setMerchantName(posInfo.getMer_name());//商户名称
            posData.setCashAmt(view.getCashAmt());
            posData.setAmount(balAmt.toString());//金额
            posData.setOrderId(order.getOrderId());
            posData.setTransType("现金支付");//交易类型

            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            posData.setDateTime(df.format(new Date()));//交易时间 格式yyyyMMddHHmmss
            if (transRecord != null) {
                //支付成功
                updRecord(2);
            } else {
                //无抵扣，支付成功，
                saveRecord(order.getOrderId(), 2, 0);
            }
            DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            model.payNotify(order.getOrderId(), "cash", "PAY", df1.format(new Date()), AmtUtils.changeY2F(posData.getCashAmt()), AmtUtils.changeY2F(balAmt.toString()), null, new MpCallBack<JSONObject, String>() {
                @Override
                public void onSuccess(JSONObject resp) {
                    view.loaded();
                    view.toast("现金支付成功");
                    print();
                }

                @Override
                public void onFailure(String resp, String message) {
                    view.loaded();
                    view.prompt(message);
                }
            });

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存交易记录
     *
     * @param orderId   订单id
     * @param state     支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @param sellState 抵扣状态  0:无抵扣(普通交易) 1:抵扣成功  2:抵扣撤销 3:全额抵扣成功
     * @return
     */
    private int saveRecord(String orderId, int state, int sellState) {
        TransRecord record = new TransRecord();
        record.setTransNo(orderId);//订单id
        record.setOrderId(orderId);//订单id
        record.setTransAmt(order.getTransAmt());//总交易金
        record.setPaidAmt(order.getPaidAmt());//实际支付金额
        record.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString() : null);//会员优惠金额
        record.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        record.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额
        record.setTransDate(posData.getDateTime().substring(0, 8));//交易日期
        record.setTransTime(posData.getDateTime().substring(8));//交易时间
        record.setState(state);
        record.setSellState(sellState);//销账成功
        record.setOrderData(JSON.toJSONString(order));
        record.setPosData(JSON.toJSONString(posData));
        transRecord = record;
        return model.saveTransRecord(record);
    }

    /**
     * 修改交易记录
     *
     * @param state 支付状态  1:支付中 2:支付成功(全单支付完成) 3:撤销中(尚有其他子订单尚未撤销成功的) 4:撤销成功(全单撤销完成)
     * @return
     */
    private int updRecord(int state) {
        transRecord.setState(state);
        transRecord.setPosData(JSON.toJSONString(posData));
        return model.updTransRecord(transRecord);
    }

    /**
     * 打印支付摘要
     */
    public void print() {
        //因为onActivityResult回来没有立即执行onResume方法
        DeviceLogin.login(view.getContext());
        view.loading("交易成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(order.getCashierNo());
        data.setOilName(order.getOilName());
        data.setOperName(order.getCashierName());
        data.setOrderId(order.getOrderId());//订单号
        data.setAmt(order.getTransAmt());//订单总金额
        data.setCardNo(order.getMemberData() != null ? order.getMemberData().getCardNo() : null);//会员卡号
        data.setDisRightsAmt(order.getMemberData() != null ? order.getMemberData().getOilDiscountAmt().toString() : null);//会员权益优惠
        data.setDisCouponAmt(order.getDisCouponAmt());//卡券使用金额
        data.setDisEWalletAmt(order.getDisEWalletAmt());//电子钱包使用金额
        data.setTime(posData.getDateTime());//交易时间
        data.setCashAmt(posData.getCashAmt());//现金交易金额
        data.setTrsAmt(posData.getAmount());//非现金交易金额
        data.setCouponUrl(model.getGlobal().getCashierData().getUrlPrefix());
        printer = PrintManager.createPrinter(PrintManager.PRINT_CASHIER, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                String printCount = order.getPrintCount();
                if (printCount == null) {
                    order.setPrintCount("1");
                } else {
                    printCount = Integer.parseInt(printCount) + 1 + "";
                    order.setPrintCount(printCount);
                }
                transRecord.setOrderData(JSON.toJSONString(order));
                model.updTransRecord(transRecord);
                view.loaded();
                view.toast("打印成功");
                view.toActivity(MainActivity.class, null);
                view.finish();
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print();
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }
}
